package com.zys.el.time.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zys.el.time.entity.AbsorbedTarget;
import com.zys.el.time.entity.Target;
import com.zys.el.time.mapper.AbsorbedTargetMapper;
import com.zys.el.time.service.IAbsorbedTargetService;
import com.zys.el.time.utils.TimeUtil;
import com.zys.el.time.vojo.AbsorbedAnalysis;
import com.zys.el.time.vojo.AbsorbedDetail;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Service
public class AbsorbedTargetService extends ServiceImpl<AbsorbedTargetMapper, AbsorbedTarget>
        implements IAbsorbedTargetService {

    @Override
    public AbsorbedAnalysis getTargetAnalysis(LocalDate firstDate, LocalDate lastDate, Long userId) {
        List<Target> targetList = this.getBaseMapper().getListByAbTargetRightJoinDeal(userId, firstDate, lastDate);

        log.debug(targetList.toString());

        HashMap<Long, AbsorbedDetail> map = new HashMap<>();
        String allAbsorbedDuration = "0:0:0";
        for (Target target : targetList) {
            Long targetId = target.getId();
            AbsorbedDetail d = null;
            if (map.containsKey(targetId)) { // 更新值
                d = map.get(targetId);
                String hourMin = TimeUtil.handleTimeBackHourMinSec(target.getAbsorbedDuration(), d.getAllMinutes());
                d.setAllMinutes(hourMin);
                // 计算这个target的专注次数
                d.setTimes(d.getTimes() + 1);
            }
            if (d == null) { // 没出现过，先赋值
                d = new AbsorbedDetail();
                d.setTargetId(target.getId());
                d.setTimes(1);
                d.setAllMinutes(target.getAbsorbedDuration());
                d.setUserId(userId);
                d.setName(target.getName());
            }
            // 计算总专注时长
            allAbsorbedDuration = TimeUtil.handleTimeBackHourMinSec(allAbsorbedDuration, target.getAbsorbedDuration());
            map.put(targetId, d);
        }

        log.debug(map.toString());
        return new AbsorbedAnalysis(userId, allAbsorbedDuration, (long) targetList.size(), new ArrayList<>(map.values()));

    }
}




